package com.ias.agdis_r.volley;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.util.S;
import android.util.Log;

/**
 * 请求网络Json资源，通过Gson转换为需要的类型T
 * 
 * @author Chipor
 *
 * @param <T>
 */
public class GsonRequest<T> extends JsonRequest<T> {

	private static final String TAG = GsonRequest.class.getSimpleName();

	private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

	private final Listener<T> mListener;
	private Class<T> clazz;

	/**
	 * 
	 * @param method
	 * @param url
	 * @param clazz需要返回数据类型的Class对象
	 * @param reqBody请求正文，为Json格式字符串
	 * @param listener成功回调
	 * @param errorListener失败回调
	 */
	public GsonRequest(int method, String url, Class<T> clazz, String reqBody, Listener<T> listener,
			ErrorListener errorListener) {
		super(method, url, reqBody, listener, errorListener);
		this.mListener = listener;
		Log.i(TAG, "Request:" + reqBody);

		// 获取范型T对应的具体Class对象，赋值给clazz
		// Type type = getClass().getGenericSuperclass();
		// Type[] params = ((ParameterizedType) type).getActualTypeArguments();
		// this.clazz = (Class<T>) params[0];

		this.clazz = clazz;
	}

	/**
	 * reqBody为空的时候发起GET请求，否则为POST请求
	 * 
	 * @param url
	 * @param clazz
	 * @param reqBody请求正文，为Json格式字符串
	 * @param listener
	 * @param errorListener
	 */
	public GsonRequest(String url, Class<T> clazz, String reqBody, Listener<T> listener, ErrorListener errorListener) {
		this(S.isEmpty(reqBody) ? Method.GET : Method.POST, url, clazz, reqBody, listener, errorListener);
		this.setRetryPolicy(new DefaultRetryPolicy(50000,
				DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
	}

	@Override
	protected void deliverResponse(T response) {
		mListener.onResponse(response);
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		try {
			String jsonString = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
			Log.i(TAG, "Response:" + jsonString);
			return Response.success(DataManager.getInstance().getMapper().readValue(jsonString, clazz), HttpHeaderParser.parseCacheHeaders(response));
		} catch (Exception e) {
			return Response.error(new ParseError(e));
		}
	}
}
